[[...path]].page.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import React, { useEffect } from 'react';
  2. import type { IUserHasId, IPagePopulatedToShowRevision } from '@growi/core';
  3. import type {
  4. GetServerSideProps, GetServerSidePropsContext,
  5. } from 'next';
  6. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  7. import Head from 'next/head';
  8. import superjson from 'superjson';
  9. import { useLayoutFluidClassNameByPage } from '~/client/services/layout';
  10. import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
  11. import GrowiContextualSubNavigationSubstance from '~/components/Navbar/GrowiContextualSubNavigation';
  12. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  13. import { ShareLinkPageView } from '~/components/ShareLinkPageView';
  14. import { SupportedAction, SupportedActionType } from '~/interfaces/activity';
  15. import type { CrowiRequest } from '~/interfaces/crowi-request';
  16. import type { RendererConfig } from '~/interfaces/services/renderer';
  17. import type { IShareLinkHasId } from '~/interfaces/share-link';
  18. import type { PageDocument } from '~/server/models/page';
  19. import {
  20. useCurrentUser, useRendererConfig, useIsSearchPage, useCurrentPathname,
  21. useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault, useIsContainerFluid, useIsEnabledMarp,
  22. } from '~/stores/context';
  23. import { useCurrentPageId, useIsNotFound, useSWRMUTxCurrentPage } from '~/stores/page';
  24. import loggerFactory from '~/utils/logger';
  25. import type { NextPageWithLayout } from '../_app.page';
  26. import {
  27. getServerSideCommonProps, generateCustomTitleForPage, getNextI18NextConfig, CommonProps, skipSSR,
  28. } from '../utils/commons';
  29. const logger = loggerFactory('growi:next-page:share');
  30. type Props = CommonProps & {
  31. shareLinkRelatedPage?: IShareLinkRelatedPage,
  32. shareLink?: IShareLinkHasId,
  33. isNotFound: boolean,
  34. isExpired: boolean,
  35. disableLinkSharing: boolean,
  36. isSearchServiceConfigured: boolean,
  37. isSearchServiceReachable: boolean,
  38. isSearchScopeChildrenAsDefault: boolean,
  39. isEnabledMarp: boolean,
  40. drawioUri: string | null,
  41. rendererConfig: RendererConfig,
  42. skipSSR: boolean,
  43. ssrMaxRevisionBodyLength: number,
  44. };
  45. type IShareLinkRelatedPage = IPagePopulatedToShowRevision & PageDocument;
  46. superjson.registerCustom<IShareLinkRelatedPage, string>(
  47. {
  48. isApplicable: (v): v is IShareLinkRelatedPage => {
  49. return v != null
  50. && v.toObject != null
  51. && v.lastUpdateUser != null
  52. && v.creator != null
  53. && v.revision != null;
  54. },
  55. serialize: (v) => { return superjson.stringify(v.toObject()) },
  56. deserialize: (v) => { return superjson.parse(v) },
  57. },
  58. 'IShareLinkRelatedPageTransformer',
  59. );
  60. // GrowiContextualSubNavigation for shared page
  61. // get page info from props not to send request 'GET /page' from client
  62. type GrowiContextualSubNavigationForSharedPageProps = {
  63. page?: IPagePopulatedToShowRevision,
  64. isLinkSharingDisabled: boolean,
  65. }
  66. const GrowiContextualSubNavigationForSharedPage = (props: GrowiContextualSubNavigationForSharedPageProps): JSX.Element => {
  67. const { page, isLinkSharingDisabled } = props;
  68. return (
  69. <GrowiContextualSubNavigationSubstance currentPage={page} isLinkSharingDisabled={isLinkSharingDisabled} />
  70. );
  71. };
  72. const SharedPage: NextPageWithLayout<Props> = (props: Props) => {
  73. useCurrentPathname(props.shareLink?.relatedPage.path);
  74. useIsSearchPage(false);
  75. useIsNotFound(props.isNotFound);
  76. useShareLinkId(props.shareLink?._id);
  77. useCurrentPageId(props.shareLink?.relatedPage._id);
  78. useCurrentUser(props.currentUser);
  79. useRendererConfig(props.rendererConfig);
  80. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  81. useIsSearchServiceReachable(props.isSearchServiceReachable);
  82. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  83. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  84. useIsContainerFluid(props.isContainerFluid);
  85. const { trigger: mutateCurrentPage, data: currentPage } = useSWRMUTxCurrentPage();
  86. useEffect(() => {
  87. if (!props.skipSSR) {
  88. return;
  89. }
  90. if (props.shareLink?.relatedPage._id != null && !props.isNotFound) {
  91. mutateCurrentPage();
  92. }
  93. }, [mutateCurrentPage, props.isNotFound, props.shareLink?.relatedPage._id, props.skipSSR]);
  94. const growiLayoutFluidClass = useLayoutFluidClassNameByPage(props.shareLinkRelatedPage);
  95. const pagePath = props.shareLinkRelatedPage?.path ?? '';
  96. const title = generateCustomTitleForPage(props, pagePath);
  97. return (
  98. <>
  99. <Head>
  100. <title>{title}</title>
  101. </Head>
  102. <div className={`dynamic-layout-root ${growiLayoutFluidClass} justify-content-between`}>
  103. <nav className="sticky-top">
  104. <GrowiContextualSubNavigationForSharedPage page={currentPage ?? props.shareLinkRelatedPage} isLinkSharingDisabled={props.disableLinkSharing} />
  105. </nav>
  106. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  107. <ShareLinkPageView
  108. pagePath={pagePath}
  109. rendererConfig={props.rendererConfig}
  110. page={currentPage ?? props.shareLinkRelatedPage}
  111. shareLink={props.shareLink}
  112. isExpired={props.isExpired}
  113. disableLinkSharing={props.disableLinkSharing}
  114. />
  115. </div>
  116. </>
  117. );
  118. };
  119. SharedPage.getLayout = function getLayout(page) {
  120. return (
  121. <>
  122. <DrawioViewerScript />
  123. <ShareLinkLayout>{page}</ShareLinkLayout>
  124. </>
  125. );
  126. };
  127. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  128. const req: CrowiRequest = context.req as CrowiRequest;
  129. const { crowi } = req;
  130. const { configManager, searchService } = crowi;
  131. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  132. props.isSearchServiceConfigured = searchService.isConfigured;
  133. props.isSearchServiceReachable = searchService.isReachable;
  134. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  135. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  136. props.rendererConfig = {
  137. isSharedPage: true,
  138. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  139. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  140. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  141. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  142. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  143. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  144. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  145. // XSS Options
  146. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  147. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  148. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  149. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  150. highlightJsStyleBorder: configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  151. };
  152. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  153. }
  154. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  155. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  156. props._nextI18Next = nextI18NextConfig._nextI18Next;
  157. }
  158. function getAction(props: Props): SupportedActionType {
  159. let action: SupportedActionType;
  160. if (props.isExpired) {
  161. action = SupportedAction.ACTION_SHARE_LINK_EXPIRED_PAGE_VIEW;
  162. }
  163. else if (props.shareLink == null) {
  164. action = SupportedAction.ACTION_SHARE_LINK_NOT_FOUND;
  165. }
  166. else {
  167. action = SupportedAction.ACTION_SHARE_LINK_PAGE_VIEW;
  168. }
  169. return action;
  170. }
  171. async function addActivity(context: GetServerSidePropsContext, action: SupportedActionType): Promise<void> {
  172. const req: CrowiRequest = context.req as CrowiRequest;
  173. const parameters = {
  174. ip: req.ip,
  175. endpoint: req.originalUrl,
  176. action,
  177. user: req.user?._id,
  178. snapshot: {
  179. username: req.user?.username,
  180. },
  181. };
  182. await req.crowi.activityService.createActivity(parameters);
  183. }
  184. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  185. const req = context.req as CrowiRequest<IUserHasId & any>;
  186. const { crowi, params } = req;
  187. const result = await getServerSideCommonProps(context);
  188. if (!('props' in result)) {
  189. throw new Error('invalid getSSP result');
  190. }
  191. const props: Props = result.props as Props;
  192. try {
  193. const ShareLinkModel = crowi.model('ShareLink');
  194. const shareLink = await ShareLinkModel.findOne({ _id: params.linkId }).populate('relatedPage');
  195. if (shareLink == null) {
  196. props.isNotFound = true;
  197. }
  198. else {
  199. props.isNotFound = false;
  200. const ssrMaxRevisionBodyLength = crowi.configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  201. props.skipSSR = await skipSSR(shareLink.relatedPage, ssrMaxRevisionBodyLength);
  202. props.shareLinkRelatedPage = await shareLink.relatedPage.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  203. props.isExpired = shareLink.isExpired();
  204. props.shareLink = shareLink.toObject();
  205. }
  206. }
  207. catch (err) {
  208. logger.error(err);
  209. }
  210. injectServerConfigurations(context, props);
  211. await injectNextI18NextConfigurations(context, props);
  212. await addActivity(context, getAction(props));
  213. return {
  214. props,
  215. };
  216. };
  217. export default SharedPage;